package com.verlet.springbootdemo.handler;

import com.verlet.springbootdemo.annotation.CurrentUser;
import com.verlet.springbootdemo.common.Constants;
import com.verlet.springbootdemo.entity.User;
import com.verlet.springbootdemo.util.ThreadLocalUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static com.verlet.springbootdemo.filter.IgnoreAuthInterceptor.TOKEN;
import static com.verlet.springbootdemo.filter.IgnoreAuthInterceptor.USER;

/**
 * 自定义 controller方法的参数绑定
 *
 * @author verlet
 * @date 2021-02-26 21:31
 * @see org.springframework.web.method.support.HandlerMethodReturnValueHandler
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {


    /**
     * 是否支持该参数
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 返回解析后的参数
     */
    @Override
    public User resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader(Constants.TOKEN);
        ThreadLocalUtil.setThreadLocalValue("这里ThreadLocalValue");
        ThreadLocalUtil.setInheritableThreadLocalValue("这里InheritableThreadLocalValue");
        if (TOKEN.equals(token)) {
            return USER;
        }
        return null;
    }
}
